package cn.iftrue.japidemo.aop;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;

@Aspect
@Component
public class MyAop {
    @Value("${project.jwt.secret}")
    private String jwt_secret;

    @Before("execution(* cn.iftrue.japidemo.controller.*.*(..))")
    public void before(){
    }

    @After("execution(* cn.iftrue.japidemo.controller.*.*(..))")
    public void after(){
        System.out.println("after...");
    }

    @Around("execution(* cn.iftrue.japidemo.controller.*.*(..)) && !execution(* cn.iftrue.japidemo.controller.*.login(..))")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        HttpServletRequest request= (HttpServletRequest)RequestContextHolder.getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String token = request.getHeader("token");

        Algorithm algorithm = Algorithm.HMAC256(jwt_secret);
        JWT.require(algorithm)
                .build()
                .verify(token);
       return proceedingJoinPoint.proceed();
    }
}
